<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>earth</title>

    <style>
        body {
            margin: 0px;
            background-color: #aaaaaa;
            overflow: hidden;
        }
    </style>
</head>

<script src="lib/three.js"></script>
<script src="lib/OrbitControls.js"></script>

<body oncontextmenu=self.event.returnValue=false>
    <div style="user-select: none;">

    </div>
</body>
    <script>

        let maxLength = 20037508.3427892;
        let r = 6378137;
        let maxB = 85.05112877980659;

        let fov = 30;
        let fovHalf = fov/2;
        let camera = new THREE.PerspectiveCamera( fov, window.innerWidth / window.innerHeight, 1, r*4 );
        let position = new THREE.Vector3(0, 0, r/Math.sin(Math.PI/12));
        camera.position.copy(position);

        let control = new THREE.OrbitControls(camera);
        control.minDistance = r;
        control.maxDistance = r*4;

        scene = new THREE.Scene();
        scene.background = new THREE.Color('#aaaaaa');

        let renderer = new THREE.WebGLRenderer( { antialias: true } );
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );
        document.body.appendChild( renderer.domElement );
        window.addEventListener( 'resize', onWindowResize, false );

        let loader = new THREE.TextureLoader();

        let geometryTest = new THREE.BoxGeometry(100000,100000,100000);
        let materialTest = new THREE.MeshBasicMaterial( {
            color: new THREE.Color('#ff0000')
        } );
        let meshTest = new THREE.Mesh( geometryTest, materialTest );
        let positionTest = lonLat2World(114,30);
        meshTest.position.copy(positionTest);
        scene.add( meshTest );

        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize( window.innerWidth, window.innerHeight );
        }

        let z = 2;

        let rect = {
            top: 0,
            bottom: 1,
            left: 0,
            right: 1,
        }

        let count = Math.pow(2, z);
        let tileWidth = maxLength*2/count;

        for(let x=0; x<count; x++){
            for(let y=0; y<count; y++){
                let mx = x * tileWidth - maxLength;
                let my = (count-1-y) * tileWidth - maxLength;
                let lb = webMercator2LonLat(mx, my);

                let mx1 = (x+1) * tileWidth - maxLength;
                let my1 = (count-y) * tileWidth - maxLength;
                let lb1 = webMercator2LonLat(mx1, my1);

                let lLength = lb1[0] - lb[0];
                let bLength = lb1[1] - lb[1];

                let geometry = getSphereGeometry(32,32, lb[0], lLength, lb[1], bLength);
                // let url = 'http://mt1.google.cn/vt/lyrs=s&hl=zh-CN&x='+x+'&y='+y+'&z='+z+'&s=Gali';
                let url = 'https://api.mapbox.com/v4/mapbox.satellite/'+z+'/'+x+'/'+y+'.webp?sku=101iGH34Pnrym&access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4M29iazA2Z2gycXA4N2pmbDZmangifQ.-g_vE53SD2WrJ6tFX7QHmA';
                let url1 = 'UV_Grid_Sm.jpg';
                let map = loader.load(url);
                map.wrapS = THREE.RepeatWrapping;
                map.wrapT = THREE.RepeatWrapping;
                // map.repeat.set(count,count);

                map.offset.set(0, 0);
                let material = new THREE.MeshBasicMaterial( {
                    map: map,
                    side: 1,
                } );
                let mesh = new THREE.Mesh( geometry, material );
                scene.add( mesh );
            }
        }


        function getSphereGeometry(widthSegments=256,heightSegments=256,startL=-180,lengthL=360,startB=-maxB,lengthB=maxB*2) {
            let pointList = [];
            let uvList = [];
            let height = lengthB/heightSegments;
            let width = lengthL/widthSegments;
            for(let b=startB,i=0; i<heightSegments; b+=height,i++){
                for(let l=startL,j=0; j<widthSegments; l+=width,j++){
                    let point = lonLat2World(l, b);
                    pointList.push(point);
                    let mercator = lonLat2WebMercator(l, b);
                    let uvx = (mercator[0]/(maxLength*2) + 0.5)*count;
                    let uvy = (mercator[1]/(maxLength*2) + 0.5)*count;
                    uvList.push(uvx, uvy);
                }
                let l = startL+lengthL;
                let point = lonLat2World(l, b);
                pointList.push(point);
                let mercator = lonLat2WebMercator(l, b);
                let uvx = (mercator[0]/(maxLength*2) + 0.5)*count;
                let uvy = (mercator[1]/(maxLength*2) + 0.5)*count;
                uvList.push(uvx, uvy);

            }
            let b = startB+lengthB;

            for(let l=startL,j=0; j<widthSegments; l+=width,j++){
                let point = lonLat2World(l, b);
                pointList.push(point);
                let mercator = lonLat2WebMercator(l, b);
                let uvx = (mercator[0]/(maxLength*2) + 0.5)*count;
                let uvy = (mercator[1]/(maxLength*2) + 0.5)*count;
                uvList.push(uvx, uvy);
            }
            let l = startL+lengthL;
            let point = lonLat2World(l, b);
            pointList.push(point);
            let mercator = lonLat2WebMercator(l, b);
            let uvx = (mercator[0]/(maxLength*2) + 0.5)*count;
            let uvy = (mercator[1]/(maxLength*2) + 0.5)*count;
            uvList.push(uvx, uvy);

            let posList = [];
            for (let i = 0; i < pointList.length; i++) {
                posList.push(pointList[i].x, pointList[i].y, pointList[i].z);
            }

            let indexList = [];
            let widthCount = widthSegments + 1;
            for (let i = 0; i < pointList.length - widthCount; i++) {
                if (i % widthCount === widthCount - 1) {
                    continue;
                }

                indexList.push(i + 1);
                indexList.push(i);
                indexList.push(i + widthCount);

                indexList.push(i + 1 + widthCount);
                indexList.push(i + 1);
                indexList.push(i + widthCount);
            }

            let position = new Float32Array(posList);
            let uv = new Float32Array(uvList);
            let index = new Uint32Array(indexList);

            let geometry = new THREE.BufferGeometry();

            // geometry.setAttribute( 'position', new THREE.BufferAttribute( position, 3 ) );
            // geometry.setAttribute( 'uv', new THREE.BufferAttribute( uv, 2 ) );
            geometry.attributes.position = new THREE.BufferAttribute( position, 3 );
            geometry.attributes.uv = new THREE.BufferAttribute( uv, 2 );
            geometry.index = new THREE.BufferAttribute( index, 1 );

            return geometry;
        }

        //经纬度转Web墨卡托
        function lonLat2WebMercator(l, b) {
            let x = l * 20037508.34/180;
            let y = Math.log(Math.tan((90+b)*Math.PI/360))/(Math.PI/180);
            y = y *20037508.34/180;
            return [x,y];
        }
        //Web墨卡托转经纬度
        function webMercator2LonLat(x, y) {
            let l = x/20037508.34*180;
            let b = y/20037508.34*180;
            b = 180/Math.PI*(2*Math.atan(Math.exp(b*Math.PI/180))-Math.PI/2);
            return [l,b];
        }

        //经纬度转世界坐标
        function lonLat2World(l, b) {
            l = l/180*Math.PI;
            b = b/180*Math.PI;
            let y = r*Math.sin(b);

            let scale = Math.cos(b);
            let x = r*Math.sin(l)*scale;
            let z = r*Math.cos(l)*scale;

            return new THREE.Vector3(x,y,z);
        }

        function getCameraHeight() {
            return camera.position.length() - r;
        }

        function getCameraBL() {
            let dirC = camera.position.clone().normalize();
            let dirP = new THREE.Vector3(dirC.x,0,dirC.z).normalize();
            let angleBCamera = dirC.angleTo(dirP);
            if(camera.position.y<0){
                angleBCamera = -angleBCamera;
            }

            let c = camera.position.length();
            let theta = (90 - fovHalf)/180*Math.PI;
            let angleBToCamera = theta - Math.acos(c*Math.cos(theta)/r);
            if(isNaN(angleBToCamera)){
                angleBToCamera = Math.acos(r/c);
            }

            let angleBMax = angleBCamera + angleBToCamera;
            let angleBMin = angleBCamera - angleBToCamera;

        }

        function getViewRect(){
            let rect = {
                top: camera.position.z - camera.position.y,
                bottom: camera.position.z + camera.position.y,
                left: camera.position.x - camera.position.y/window.innerHeight*window.innerWidth,
                right: camera.position.x + camera.position.y/window.innerHeight*window.innerWidth,
            }
        }

        function updateTiles() {
            let cameraHeight = getCameraHeight();
            let z = Math.ceil(Math.log2(r*4/cameraHeight));

        }

        function animate() {
            requestAnimationFrame( animate );
            renderer.render( scene, camera );
        }
        animate();

    </script>

</html>